package com.kevin.demo.service.log.impl;


import com.kevin.demo.constants.BizEnum;
import com.kevin.demo.constants.OprEnum;
import com.kevin.demo.dao.log.BizLogDao;
import com.kevin.demo.entity.log.BizLog;
import com.kevin.demo.service.log.BizLogService;
import com.kevin.demo.utils.FastJsonUtils;
import com.kevin.demo.utils.ReflectionUtil;
import com.kevin.demo.utils.StrUtil;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.List;
import java.util.Map;

/**
 * @author: e20160504
 * @date: 2018/8/27
 * @desc
 */
@Service
public class BizLogServiceImpl implements BizLogService {

    @Autowired
    private BizLogDao dao;

    //private String  token = (String) RequestContextHolder.getRequestAttributes().getAttribute("spring-token", RequestAttributes.SCOPE_REQUEST);

/**
*@params: 新旧对象，业务名称，操作，排除对比的字段
*@return:
*@desc: 插入日志
*/
    @Override
    public void insert(Object oldObj, Object newObj, BizEnum bizEnum, String operation, List<String> uncluedCols, List<String> updateCols) throws Exception {
        String  token = (String) RequestContextHolder.getRequestAttributes().getAttribute("spring-token", RequestAttributes.SCOPE_REQUEST);
        BizLog bizLog = new BizLog();
        List<Map<String, Object>> changelist;
        bizLog.setOldobject(FastJsonUtils.toJson(oldObj));
        bizLog.setNewobject(FastJsonUtils.toJson(newObj));
        bizLog.setBizname(bizEnum.getBizname());
        bizLog.setBiztype(bizEnum.getBiztype());
        bizLog.setOprCode("admin");
        bizLog.setOprName("admin");
        StringBuilder str = new StringBuilder();
        if(oldObj == null){
            str.append(OprEnum.SAVE);
            bizLog.setOperation(OprEnum.SAVE);
            bizLog.setOprContent(FastJsonUtils.toJson(newObj));
        }else{
            bizLog.setOperation(operation);
            changelist = ReflectionUtil.compareTwoClass(oldObj, newObj, uncluedCols,updateCols,ApiModelProperty.class);

            for (Map<String, Object> map : changelist) {
                str.append("【" + map.get("name") + "】从【" + map.get("old") + "】改为了【" + map.get("new") + "】\n");
            }
            bizLog.setOprContent(str.toString());
        }
        if(StrUtil.isEmpty(str.toString())){
            return;
        }
        dao.insertSelective(bizLog);
    }
}
